package pers.chao.boxing.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import pers.chao.tool.http.StatusCode;

import java.io.Serializable;

/**
 * Description: 响应包装类，待同步更新...
 *
 * @author W.Chao
 * @date 2020/10/31 15:59
 **/
public class Response<T> implements Serializable {
	private static final long serialVersionUID = -1L;
	// 自定义错误码
	private Integer code;
	// 错误码描述信息
	private String description;
	// 响应数据
	private T data;
	@JsonInclude(JsonInclude.Include.NON_NULL)
	private String datetime;

	public Response(StatusCode responseCode, T data) {
		this.code = responseCode.getCode();
		this.description = responseCode.getDesc();
		this.data = data;
	}

	/**
	 * 无数据成功请求
	 *
	 * @return
	 */
	public static Response<Void> success() {
		return new Response<Void>(StatusCode.SUCCESS, null);
	}

	/**
	 * 有数据成功请求
	 *
	 * @param data
	 * @param <T>
	 * @return
	 */
	public static <T> Response<T> success(T data) {
		return new Response<T>(StatusCode.SUCCESS, data);
	}

	/**
	 * 自定义响应状态成功请求，数据未知
	 *
	 * @param responseCode
	 * @param data
	 * @param <T>
	 * @return
	 */
	public static <T> Response<T> success(StatusCode responseCode, T data) {
		if (null == data) {
			return success(data);
		}
		return new Response<T>(responseCode, data);
	}

	/**
	 * 无数据服务异常失败请求
	 *
	 * @param <T>
	 * @return
	 */
	public static <T> Response<T> failure() {
		return new Response<T>(StatusCode.INTERNAL_SERVER_ERROR, null);
	}

	/**
	 * 无数据自定义异常失败请求
	 *
	 * @param responseCode
	 * @param <T>
	 * @return
	 */
	public static <T> Response<T> failure(StatusCode responseCode) {
		if (null == responseCode) {
			return failure();
		}
		return new Response<T>(responseCode, null);
	}

	/**
	 * 自定义异常失败请求，数据未知
	 *
	 * @param responseCode
	 * @param data
	 * @param <T>
	 * @return
	 */
	public static <T> Response<T> failure(StatusCode responseCode, T data) {
		if (null == data) {
			return failure();
		}
		return new Response<T>(responseCode, data);
	}

	public Integer getCode() {
		return code;
	}

	public String getDescription() {
		return description;
	}

	public T getData() {
		return data;
	}

	public String getDatetime() {
		return datetime;
	}

	public void setDatetime(String datetime) {
		this.datetime = datetime;
	}

	@Override
	public String toString() {
		return "Response{" +
				"code=" + code +
				", description='" + description + '\'' +
				", data=" + data +
				", datetime='" + datetime + '\'' +
				'}';
	}
}
